import type { TaskList, Task } from '@/types/taskList';

const getFromLocalStorage = (): TaskList[] => {
    const data = localStorage.getItem('taskLists');
    return data ? JSON.parse(data) : [];
};

export const saveToLocalStorage = (data: TaskList[]) => {
    localStorage.setItem('taskLists', JSON.stringify(data));
};

let taskLists: TaskList[] = getFromLocalStorage();

const generateId = () => `id-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;

const initDefaultData = () => {
    if (taskLists.length === 0) {
        taskLists.push({
            id: generateId(),
            name: '我的任务',
            editingName: false,
            visible: true,
            isTitleVisible: true,
            animationState: 'idle',
            tasks: [],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        });
        saveToLocalStorage(taskLists);
    }
};

export const getAllTaskLists = async (): Promise<TaskList[]> => {
    initDefaultData();
    return JSON.parse(JSON.stringify(taskLists));
};

export const createTaskList = async (name: string): Promise<TaskList> => {
    const newList: TaskList = {
        id: generateId(),
        name: name.trim() || '未命名列表',
        editingName: false,
        visible: true,
        isTitleVisible: true,
        animationState: 'idle',
        tasks: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    taskLists.push(newList);
    saveToLocalStorage(taskLists);
    return JSON.parse(JSON.stringify(newList));
};

export const updateTaskListName = async (listId: string, newName: string): Promise<TaskList> => {
    const list = taskLists.find(l => l.id === listId);
    if (!list) throw new Error('任务列表不存在');

    list.name = newName.trim() || '未命名列表';
    list.updatedAt = new Date().toISOString();
    saveToLocalStorage(taskLists);
    return JSON.parse(JSON.stringify(list));
};

export const toggleTaskListVisibility = async (listId: string, visible: boolean): Promise<TaskList> => {
    const list = taskLists.find(l => l.id === listId);
    if (!list) throw new Error('任务列表不存在');

    list.visible = visible;
    list.updatedAt = new Date().toISOString();
    saveToLocalStorage(taskLists);
    return JSON.parse(JSON.stringify(list));
};

export const addTask = async (listId: string, task: Omit<Task, 'id' | 'createdAt' | 'updatedAt'>): Promise<Task> => {
    const list = taskLists.find(l => l.id === listId);
    if (!list) throw new Error('任务列表不存在');

    const newTask: Task = {
        id: generateId(),
        ...task,
        completed: task.completed ?? false,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };

    list.tasks.push(newTask);
    list.updatedAt = new Date().toISOString();
    saveToLocalStorage(taskLists);
    return JSON.parse(JSON.stringify(newTask));
};

export const updateTask = async (listId: string, taskId: string, updates: Partial<Task>): Promise<Task> => {
    const list = taskLists.find(l => l.id === listId);
    if (!list) throw new Error('任务列表不存在');

    const task = list.tasks.find(t => t.id === taskId);
    if (!task) throw new Error('任务不存在');

    const updatedTask = {
        ...task,
        ...updates,
        updatedAt: new Date().toISOString()
    };

    const taskIndex = list.tasks.findIndex(t => t.id === taskId);
    list.tasks[taskIndex] = updatedTask;
    list.updatedAt = new Date().toISOString();
    saveToLocalStorage(taskLists);
    return JSON.parse(JSON.stringify(updatedTask));
};

export const deleteTask = async (listId: string, taskId: string): Promise<void> => {
    const list = taskLists.find(l => l.id === listId);
    if (!list) throw new Error('任务列表不存在');

    list.tasks = list.tasks.filter(t => t.id !== taskId);
    list.updatedAt = new Date().toISOString();
    saveToLocalStorage(taskLists);
};

export const deleteTaskList = async (listId: string): Promise<void> => {
    taskLists = taskLists.filter(l => l.id !== listId);
    saveToLocalStorage(taskLists);
};

export const updateTaskListOrder = async (updatedLists: TaskList[]): Promise<void> => {
    taskLists = [...updatedLists];
    saveToLocalStorage(taskLists);
};

export const updateTaskListAnimation = async (listId: string, animationState: string, isTitleVisible: boolean) => {
    const list = taskLists.find(l => l.id === listId);
    if (!list) throw new Error('任务列表不存在');
    list.animationState = animationState as any;
    list.isTitleVisible = isTitleVisible;
    list.updatedAt = new Date().toISOString();
    saveToLocalStorage(taskLists);
    return list;
};

